package com.control.servlet;

import com.dao.GoodsDao;
import com.dao.ShoppingcartDao;
import com.model.Shoppingcart;
import com.model.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class shoppingcartServlet extends HttpServlet {

    ShoppingcartDao shoppingcartDao = new ShoppingcartDao();

    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        if("delete".equals(action)){
            String shoppingcartId = req.getParameter("shoppingcartId");
            int result = shoppingcartDao.deleteShoppingcartByShoppingcartId(shoppingcartId);
            if(result>0){
                resp.sendRedirect("/store/jsp/shoppingCart.jsp");
            }
            else {
                resp.sendRedirect("/store/jsp/shoppingCart.jsp");
            }
        }

        else if(("add").equals(action) ){
            HttpSession session = req.getSession();
            User user = (User) session.getAttribute("user");
            String userId = user.getId();
            String goodsId = req.getParameter("goodsId");
            String number = req.getParameter("goods_num");
            int res = shoppingcartDao.addGoodsToShoppingcart(userId,goodsId,number);
            if(res>0){
                resp.sendRedirect("/store/jsp/goods.jsp?goodsId="+goodsId);
            }
            else {
                resp.sendRedirect("/store/jsp/goods.jsp?goodsId="+goodsId);
            }
        }

        else if("numAdd".equals(action)){
            PrintWriter out = resp.getWriter();
            String id = req.getParameter("shoppingCartId");
            int result = shoppingcartDao.addShoppingCartNum(id);
            if(result>0){
                out.write(shoppingcartDao.getShoppingcartByShoppingCartId(id).getNumber());
            }
            else {
                resp.sendRedirect("/store/jsp/shoppingcart.jsp");
            }
        }

        else if("numSub".equals(action)){
            PrintWriter out = resp.getWriter();
            String id = req.getParameter("shoppingCartId");
            int result = shoppingcartDao.subShoppingCartNum(id);
            if(result>0){
                out.write(shoppingcartDao.getShoppingcartByShoppingCartId(id).getNumber());
            }
            else {
                resp.sendRedirect("/store/jsp/shoppingcart.jsp");
            }
        }

    }
}
